package com.zhou.cloud.controller;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @descrition: ES测试接口
 * @author: zhouyongjun
 * @date: 2022/9/24
 **/
@RestController
@RequestMapping("es")
public class ESController {
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @RequestMapping("find")
    public JSONObject find() throws IOException {
        SearchRequest searchRequest = new SearchRequest("sq_*");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.queryStringQuery("127.0.0.1"))
                .sort("timestamp", SortOrder.fromString("desc"));
        System.out.println("searchSourceBuilder =" + searchSourceBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(JSONObject.toJSON(hits));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",0);
        return jsonObject;
    }

    @RequestMapping("bank/query")
    public String bankQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("bank");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.size(10);
        System.out.println("searchSourceBuilder =" + searchSourceBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(JSONObject.toJSON(hits));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",0);
        jsonObject.put("hints",JSONObject.toJSON(hits));
        return jsonObject.toJSONString();
    }

    /**
    * @Description: match 匹配查询 ，支持分页，排序
     * 用 空格 可以实现 或查询 比如： value=mill lane
     * 测试请求：http://localhost:19001/es/index/query/match?name=address&value=mill lane&pageNum=10&page=2&sortName=account_number&index=bank
    * @Params:
    String index: 索引名字（数据库）
    String name: 匹配字段
    String value: 匹配值
    int pageNum: 查询结果数量
    int page: 页数
    String sortName: 排序字段
    String sortOrderParam: 排序类型 asc顺序否则倒序
     * @Returns:
    * @Author: zhouyongjun
    * @Date Created in 2022/9/28 15:25
     */
    @RequestMapping("index/query/match")
    public String match(String index,String name,String value,int pageNum,int page,String sortName,String sortOrderParam) throws IOException {

        SearchRequest searchRequest = new SearchRequest(index);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //命令
        searchSourceBuilder.query(QueryBuilders.matchQuery(name,value));
        //分页
        if(page > 0) {
            searchSourceBuilder.size(pageNum);
            searchSourceBuilder.from((Math.max(page, 1) - 1) * pageNum);
        }
        //排序
        if (StringUtils.isNotBlank(sortName))
        {
            SortOrder sortOrder = SortOrder.ASC;
            if(StringUtils.isNotBlank(sortOrderParam))
            {
                sortOrder = sortOrderParam.equalsIgnoreCase("asc")  ? SortOrder.ASC : SortOrder.DESC;
            }
            searchSourceBuilder.sort(sortName,sortOrder);
        }
        System.out.println("searchSourceBuilder =" + searchSourceBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(JSONObject.toJSON(hits));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",0);
        jsonObject.put("hints",JSONObject.toJSON(hits));
        return jsonObject.toJSONString();
    }


    /**
     * @Description: match_phrase 全匹配查询，支持分页，排序
     * 测试请求：http://localhost:19001/es/index/query/match_phrase?name=address&value=mill lane&pageNum=10&page=1&sortName=account_number&index=bank
     * @Params:
    String index: 索引名字（数据库）
    String name: 匹配字段
    String value: 匹配值
    int pageNum: 查询结果数量
    int page: 页数
    String sortName: 排序字段
    String sortOrderParam: 排序类型 asc顺序否则倒序
     * @Returns:
     * @Author: zhouyongjun
     * @Date Created in 2022/9/28 15:25
     */

    @RequestMapping("index/query/match_phrase")
    public String matchPhrase(String index,String name,String value,int pageNum,int page,String sortName,String sortOrderParam) throws IOException {

        SearchRequest searchRequest = new SearchRequest(index);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //命令
        searchSourceBuilder.query(QueryBuilders.matchPhraseQuery(name,value));
        //分页
        if(page > 0) {
            searchSourceBuilder.size(pageNum);
            searchSourceBuilder.from((Math.max(page, 1) - 1) * pageNum);
        }
        //排序
        if (StringUtils.isNotBlank(sortName))
        {
            SortOrder sortOrder = SortOrder.ASC;
            if(StringUtils.isNotBlank(sortOrderParam))
            {
                sortOrder = sortOrderParam.equalsIgnoreCase("asc")  ? SortOrder.ASC : SortOrder.DESC;
            }
            searchSourceBuilder.sort(sortName,sortOrder);
        }
        System.out.println("searchSourceBuilder =" + searchSourceBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(JSONObject.toJSON(hits));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",0);
        jsonObject.put("hints",JSONObject.toJSON(hits));
        return jsonObject.toJSONString();
    }


    /**
     * @Description: match bool 多条件匹配查询，支持分页，排序
     * 测试请求：http://localhost:19001/es/index/query/match_phrase?name=address&value=mill lane&pageNum=10&page=1&sortName=account_number&index=bank
     * @Params:
    String index: 索引名字（数据库）
    String name: 匹配字段
    String value: 匹配值
    int pageNum: 查询结果数量
    int page: 页数
    String sortName: 排序字段
    String sortOrderParam: 排序类型 asc顺序否则倒序
     * @Returns:
     * @Author: zhouyongjun
     * @Date Created in 2022/9/28 15:25
     */
    @RequestMapping("index/query/match_bool")
    public String matchBool(String index,String name,String value,int pageNum,int page,String sortName,String sortOrderParam) throws IOException {

        SearchRequest searchRequest = new SearchRequest(index);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //命令 多条件匹配
        searchSourceBuilder.query(QueryBuilders.boolQuery()
                .must(QueryBuilders.matchQuery("age","40"))
                .mustNot(QueryBuilders.matchQuery("state","ID")));
        //分页
        if(page > 0) {
            searchSourceBuilder.size(pageNum);
            searchSourceBuilder.from((Math.max(page, 1) - 1) * pageNum);
        }
        //排序
        if (StringUtils.isNotBlank(sortName))
        {
            SortOrder sortOrder = SortOrder.ASC;
            if(StringUtils.isNotBlank(sortOrderParam))
            {
                sortOrder = sortOrderParam.equalsIgnoreCase("asc")  ? SortOrder.ASC : SortOrder.DESC;
            }
            searchSourceBuilder.sort(sortName,sortOrder);
        }
        System.out.println("searchSourceBuilder =" + searchSourceBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(JSONObject.toJSON(hits));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",0);
        jsonObject.put("hints",JSONObject.toJSON(hits));
        return jsonObject.toJSONString();
    }
}


